<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 输入内容 -->
    <input type=" placeholder="请输入内容">
    <!-- 发请求 -->
    <button>发送请求</button>
    <!-- 显示结果 -->
    <div></div>
  </body>
  <script>
    var input = document.querySelector("input");
    var button = document.querySelector("button");
    var div = document.querySelector("div");

    //1.创建websocket
    //参数1：websocket的服务地址
    var socket = new WebSocket("ws://echo.websocket.org");

    //2.open:当前websocket服务器连接成功的时候触发
    socket.addEventListener("open", function () {
      div.innerHTML = "连接成功";
    });

    //3.主动的给websocket服务发送消息
    button.addEventListener("click", function () {
      var value = input.value;
      socket.send(value);
    });

    //4.接受websocket服务的数据
    socket.addEventListener("message", function (e) {
      console.log(e.data);
      div.innerHTML = e.data;
    });

    socket.addEventListener("close", function () {
      div.innerHTML = "连接关闭";   
    });
  </script>
  <style>
    div {
      width: 300px;
      height: 300px;
      border: 1px solid #000;
    }
  </style>
</html>
